<?php


class CIniReader implements \ArrayAccess
{
    const CONFIG_FILE_SUFFIX = ".ini";

    use CoreTraitArrayAccess;

    /**
     * @param $file
     * @param string $section
     * @return static
     * @throws Exception
     */
    public static function getConfig($file, string $section = ''): static
    {

        $has_section = strlen($section) > 0;

        $filename = CONFIG_ROOT . $file . static::CONFIG_FILE_SUFFIX;

        if (!is_readable($filename)) throw new Exception($filename . ' is not readable');

        $ini = parse_ini_file($filename, $has_section);

        if ($ini === false) throw new Exception('parse error');

        $config = $has_section ? $ini[$section] ?? [] : $ini;

        return new static($config);

    }

}